import { project } from '@alilc/lowcode-engine';

export const stringToDOM = (htmlString) => {
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = htmlString; // 将 HTML 字符串放入 div 中
  return tempDiv.childNodes; // 返回所有子节点
};
// 更新props
export const updateProp = (prop, value) => {
  let schema = window.AliLowCodeEngine.project.exportSchema();
  schema.componentsTree[0].children[0].props[prop] = value;
  window.AliLowCodeEngine.project.importSchema(schema);
  // 优化重新渲染
  project.simulatorHost?.rerender();
};
// 获取图片主色调
export const getDominantColor = (imageUrl, callback) => {
  const img = new Image();
  img.src = imageUrl;
  img.crossOrigin = '';
  img.onload = function () {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);

    const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
    const colorCounts = {};
    for (let i = 0; i < data.length; i += 4) {
      const color = `rgb(${data[i]}, ${data[i + 1]}, ${data[i + 2]})`;
      colorCounts[color] = (colorCounts[color] || 0) + 1;
    }

    const dominantColor = Object.keys(colorCounts).reduce((a, b) =>
      colorCounts[a] > colorCounts[b] ? a : b
    );
    callback(dominantColor);
  };
};
// 下载
export const downloadFile = (url, fileName) => {
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};
